package com.system.core.idgenerator;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class IdGeneratorService {
	
	@Resource
	private SequenceFactory sequenceFactory;

	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");

	@Transactional(rollbackFor = Exception.class)
	public String generatorId() {
		return generatorId("");
	}

	public String generatorId(String prefix) {
		DecimalFormat numberFormat = new DecimalFormat("00000000");
		DecimalFormat radonFormat = new DecimalFormat("00");
//		return prefix+format.format(Calendar.getInstance().getTime())+numberFormat.format(idfromdb());
		Calendar expireTime = Calendar.getInstance();
		expireTime.set(Calendar.HOUR_OF_DAY, 24);
		expireTime.set(Calendar.MINUTE, 0);
		expireTime.set(Calendar.SECOND, 0);
		expireTime.set(Calendar.MILLISECOND, 0);
		int random1 = (int) (Math.random() * 100);
		int random2 = (int) (Math.random() * 100);
		return prefix + format.format(Calendar.getInstance().getTime()) + radonFormat.format(random1)
				+ numberFormat.format(sequenceFactory.generate("liaoken-sequence", expireTime.getTime()))
				+ radonFormat.format(random2);
	}
	
	private String generatorUserId(String prefix) {
		DecimalFormat numberFormat = new DecimalFormat("00000000");
		DecimalFormat radonFormat = new DecimalFormat("00");
		Calendar expireTime = Calendar.getInstance();
		expireTime.set(Calendar.HOUR_OF_DAY, 24);
		expireTime.set(Calendar.MINUTE, 0);
		expireTime.set(Calendar.SECOND, 0);
		expireTime.set(Calendar.MILLISECOND, 0);
		int random1 = (int) (Math.random() * 100);
		int random2 = (int) (Math.random() * 100);
		return prefix + format.format(Calendar.getInstance().getTime()) + radonFormat.format(random1)
				+ numberFormat.format(sequenceFactory.generate("user-id-sequence", expireTime.getTime()))
				+ radonFormat.format(random2);
	}
	
	public String generatorUserId() {
		return generatorUserId("U");
	}

}
